import React, { useState } from "react";
import fishTokenContract from "../fishToken";
import web3 from "../web3";

const RegisterFish = () => {
    const [species, setSpecies] = useState("");
    const [location, setLocation] = useState("");
    const [temperature, setTemperature] = useState("");
    const [message, setMessage] = useState("");

    const registerFish = async () => {
        try {
            const accounts = await web3.eth.getAccounts();
            if (accounts.length === 0) {
                alert("请连接钱包");
                return;
            }

            const tx = await fishTokenContract.methods
                .registerFish(species, location, parseInt(temperature, 10))
                .send({ from: accounts[0] });

            setMessage(`鱼注册成功！鱼ID: ${tx.events.FishRegistered.returnValues.id}`);
        } catch (error) {
            setMessage(`注册失败: ${error.message}`);
        }
    };

    return (
        <div>
            <h2>注册鱼</h2>
            <input
                type="text"
                placeholder="鱼的种类"
                value={species}
                onChange={(e) => setSpecies(e.target.value)}
            />
            <input
                type="text"
                placeholder="捕捞地点"
                value={location}
                onChange={(e) => setLocation(e.target.value)}
            />
            <input
                type="number"
                placeholder="捕捞温度"
                value={temperature}
                onChange={(e) => setTemperature(e.target.value)}
            />
            <button onClick={registerFish}>注册</button>
            {message && <p>{message}</p>}
        </div>
    );
};

export default RegisterFish;

